package com.android.openapp.ui;





import java.util.HashMap;
import com.android.openapp.services.Controller;
import com.android.openapp.services.Controller.ControllerBinder;
import com.android.openapp.R;
import com.google.android.maps.MapView;
import data.Place;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.TabHost;
import android.widget.Toast;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;

/**
 * Usando le librerie support.v4.googlemaps (hackate) la classe FragmentActivity
 * estende MapActivity. e' quindi possibile usare una MapView all'interno di un Fragment.
 * @author Simone Panza
 * date 2012_08_28
 */
public class MainActivity extends FragmentActivity{
	
	
	
	TabHost mTabHost;
	TabManager mTabManager;
	
	ControllerBinder mBinder;
	ProgressDialog pd;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        
        ConnectivityManager cm =
                (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
         
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork.isConnectedOrConnecting();
        if(isConnected==true){
        //BArra progresso e richiamo di DownloadThread
        pd = ProgressDialog.show(this, "Scaricamento dati..", "Scarico i Metadati", true, false);
        DownloadThread t=new DownloadThread();
		t.execute("Download metadati");
        }
        else{
        	pd = ProgressDialog.show(this, "Errore", "Connesione dati non attiva", true, false);
        }
       /* 
        // set up tabs
        mTabHost = (TabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup();
        
        mTabManager = new TabManager(this, mTabHost, R.id.realtabcontent);
        
        //add tabs
        mTabManager.addTab(mTabHost.newTabSpec("interest_places").setIndicator("Luoghi di interesse"),
        		PlacesListFragment.class, null);
        mTabManager.addTab(mTabHost.newTabSpec("map").setIndicator("Mappa"),
        		MapFragment.class,null);
        mTabManager.addTab(mTabHost.newTabSpec("settings").setIndicator("Impostazioni"),
        		SettingsFragment.class,null);
        
        //binding al Controller (service)
        Intent i = new Intent(this, Controller.class);
        bindService(i, conn, Context.BIND_AUTO_CREATE);
        
        initializeMapView();
        */
    }
    protected void createTabView(){
    	// set up tabs
        mTabHost = (TabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup();
        
        mTabManager = new TabManager(this, mTabHost, R.id.realtabcontent);
        
        //add tabs
        mTabManager.addTab(mTabHost.newTabSpec("interest_places").setIndicator("Luoghi di interesse"),
        		PlacesListFragment.class, null);
        mTabManager.addTab(mTabHost.newTabSpec("map").setIndicator("Mappa"),
        		MapFragment.class,null);
        mTabManager.addTab(mTabHost.newTabSpec("settings").setIndicator("Impostazioni"),
        		SettingsFragment.class,null);
        
        //binding al Controller (service)
        Intent i = new Intent(this, Controller.class);
        bindService(i, conn, Context.BIND_AUTO_CREATE);
        
        initializeMapView();
    }
    @Override
    protected void onResume() {
    	// TODO Auto-generated method stub
    	super.onResume();
    }
    protected void onDestroy() {
    	super.onDestroy();
    	unbindService(conn);
    }
    
    
    public void showToast(String text) {
		Log.i("HTTP DOWNLOADER", "DOWNLOAD COMPLETED, TOAST FUNCTION");
		Toast.makeText(this, "The operation returned:\n" + text, Toast.LENGTH_LONG).show();
	} 
    /**
     * Oggetto di tipo ServiceConnection che gestisce il binding/unbinding al servizio Controller
     */
    ServiceConnection conn = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mBinder = (ControllerBinder) service;
			// chiamo il fragment che gestisce la lista e la aggiorno
			PlacesListFragment frag = (PlacesListFragment) getSupportFragmentManager().findFragmentByTag("interest_places");
			frag.updateNearPlaces(mBinder);
		}
	};
    
	/**
	 * Premendo il tasto Option compare il menu:
	 * TODO lasciamo il tab dei settings o sfruttiamo il tasto Option?
	 */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    /*
     * Methods for MapActivity
     * Using the hacked support library v4: FragmentActivity extends MapActivity
     * so we can show a MapView into a Fragment.
     */
    
    @Override
    protected boolean isRouteDisplayed() {
    	return false;
    }
    
	View mMapViewContainer;
	MapView mMapView;
    
    private void initializeMapView(){
    	mMapViewContainer = LayoutInflater.from(this).inflate(R.layout.maplayout, null);
    	mMapView = (MapView) mMapViewContainer.findViewById(R.id.mapview);
    }
    
    /**
     * This is a helper class that implements a generic mechanism for
     * associating fragments with the tabs in a tab host.  It relies on a
     * trick.  Normally a tab host has a simple API for supplying a View or
     * Intent that each tab will show.  This is not sufficient for switching
     * between fragments.  So instead we make the content part of the tab host
     * 0dp high (it is not shown) and the TabManager supplies its own dummy
     * view to show as the tab content.  It listens to changes in tabs, and takes
     * care of switch to the correct fragment shown in a separate content area
     * whenever the selected tab changes.
     */
    public static class TabManager implements TabHost.OnTabChangeListener {
        private final FragmentActivity mActivity;
        private final TabHost mTabHost;
        private final int mContainerId;
        private final HashMap<String, TabInfo> mTabs = new HashMap<String, TabInfo>();
        TabInfo mLastTab;

        static final class TabInfo {
            private final String tag;
            private final Class<?> clss;
            private final Bundle args;
            private Fragment fragment;

            TabInfo(String _tag, Class<?> _class, Bundle _args) {
                tag = _tag;
                clss = _class;
                args = _args;
            }
        }

        static class DummyTabFactory implements TabHost.TabContentFactory {
            private final Context mContext;

            public DummyTabFactory(Context context) {
                mContext = context;
            }

            @Override
            public View createTabContent(String tag) {
                View v = new View(mContext);
                v.setMinimumWidth(0);
                v.setMinimumHeight(0);
                return v;
            }
        }

        public TabManager(FragmentActivity activity, TabHost tabHost, int containerId) {
            mActivity = activity;
            mTabHost = tabHost;
            mContainerId = containerId;
            mTabHost.setOnTabChangedListener(this);
        }

        public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) {
            tabSpec.setContent(new DummyTabFactory(mActivity));
            String tag = tabSpec.getTag();

            TabInfo info = new TabInfo(tag, clss, args);

            // Check to see if we already have a fragment for this tab, probably
            // from a previously saved state.  If so, deactivate it, because our
            // initial state is that a tab isn't shown.
            info.fragment = mActivity.getSupportFragmentManager().findFragmentByTag(tag);
            if (info.fragment != null && !info.fragment.isDetached()) {
                FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
                ft.detach(info.fragment);
                ft.commit();
            }

            mTabs.put(tag, info);
            mTabHost.addTab(tabSpec);
        }

        @Override
        public void onTabChanged(String tabId) {
            TabInfo newTab = mTabs.get(tabId);
            if (mLastTab != newTab) {
                FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
                if (mLastTab != null) {
                    if (mLastTab.fragment != null) {
                        ft.detach(mLastTab.fragment);
                    }
                }
                if (newTab != null) {
                    if (newTab.fragment == null) {
                        newTab.fragment = Fragment.instantiate(mActivity,
                                newTab.clss.getName(), newTab.args);
                        ft.add(mContainerId, newTab.fragment, newTab.tag);
                    } else {
                        ft.attach(newTab.fragment);
                    }
                }

                mLastTab = newTab;
                ft.commit();
                mActivity.getSupportFragmentManager().executePendingTransactions();
            }
        }
    }
 
   
private class DownloadThread extends AsyncTask<String, Integer, Integer> {
    	/**
    	 * @author Allieri Tommaso
    	 * classe che gestisce il download dei metadati
    	 * per l'aggiunta di un nuovo dataset di metadati vedere la classe Place.
    	 */
    	
	
 
    	public DownloadThread() {
    		
    		super();
    		Metainit.flag=0;
    		
    	}
    	
    	
    
    @Override
    protected Integer doInBackground(String... params) {
    	//pd.setMessage(params[0]);
    	//Message message = new Message();
    	Log.i("LVUpdate/DOWNLOAD Thread", " *** Avvio della procedura di download ***  ");
    	//
    	for(Integer i=0;i<Place.datasetM.length;i++){
    		Log.d("datasetM",Place.datasetM[i]);
    		
    		Metainit t=new Metainit(i);
    		t.setPriority(Thread.MAX_PRIORITY-i);    		
    		t.start();
    		
    		Log.d("t","Thread partito"+t.getName());
    		
    		publishProgress(i);
    	}
    	
    	while(Metainit.worked!=Place.datasetM.length){
    		Log.i("DownloadThread","waiting");
    	}
    	return Metainit.flag;
    	
    }
    @Override
    protected void onProgressUpdate(Integer...values) {
    	pd.setMessage("MultiThread Metadata download Working"+Integer.toString(values[0]));
    	super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(Integer result) {
    	if(result!=Place.datasetM.length){
    		pd.dismiss();
    		Log.e("LVUpdate/UIActivity", "DOWNLOAD HAS RAISED AN ERROR");
    		showToast("ERRORE nello scaricamento dei Metadati");
    		Metainit.worked=0;
    		Metainit.flag=0;
    	}else{
    		pd.dismiss();
    		Log.d("DOWNLOAD FINISHED", "DOWNLOAD SUCCESFULLY COMPLETED!");
    		showToast("Scaricamento Metadati eseguito con successo");
    		createTabView();
    		Metainit.worked=0;
    		Metainit.flag=0;
    	}
    		
    	super.onPostExecute(result);
    }
    @Override
    protected void onPreExecute() {
    //Inizilizzo l'arraylist dei metadati in Place
    Place.initialize();
    super.onPreExecute();
    }






    }
}
